<template>
  <div class="setting-container">
    <el-card class="box-card">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="角色管理" name="role">
          <el-row>
            <el-button
              v-if="checkPoint('POINT-ROLE-ADD')"
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="showDialog = true"
              >新增角色</el-button
            >
          </el-row>
          <el-table
            :data="roleData"
            border
            style="width: 100%"
            v-loading="loading"
          >
            <el-table-column width="175" label="序号">
              <template slot-scope="scope">
                {{ scope.$index + (pageInfo.page - 1) * pageInfo.pagesize + 1 }}
              </template>
            </el-table-column>
            <el-table-column sortable prop="name" label="角色名" width="175">
            </el-table-column>
            <el-table-column sortable prop="description" label="描述">
            </el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              width="280"
              align="center"
            >
              <template slot-scope="{ row }">
                <el-button
                  type="text"
                  size="small"
                  @click="showPermission(row.id)"
                  >分配权限</el-button
                >
                <el-button type="text" size="small" @click="editRole(row.id)"
                  >修改</el-button
                >
                <el-button type="text" size="small" @click="delRole(row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="pageInfo.page"
            @current-change="getRoleList"
            :page-size="pageInfo.pagesize"
            layout="total, prev, pager, next"
            :total="pageInfo.total"
            style="text-align: center; margin-top: 10px"
          >
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="公司信息" name="company">
          <el-form
            ref="form"
            :model="form"
            label-width="80px"
            style="width: 480px; margin: 0 auto"
          >
            <el-form-item label="企业名称">
              <el-input v-model="form.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="公司地址">
              <el-input v-model="form.companyAddress" disabled></el-input>
            </el-form-item>
            <el-form-item label="公司电话">
              <el-input v-model="form.companyPhone" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="form.mailbox" disabled></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="form.remarks" disabled></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog :title="title" :visible="showDialog" @close="cancelBtn">
      <el-form ref="roleForm" :model="roleForm" :rules="rules">
        <el-form-item label="角色名称" prop="name" label-width="120px">
          <el-input v-model.trim="roleForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description" label-width="120px">
          <el-input
            v-model.trim="roleForm.description"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelBtn">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="分配权限"
      :visible.sync="showPermDialog"
      @close="cancelPerm"
    >
      <el-tree
        ref="tree"
        :data="treeData"
        check-strictly
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="checkedKeys"
        :props="defaultProps"
        v-loading="treeloading"
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelPerm">取 消</el-button>
        <el-button type="primary" @click="updatePermission">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllRoles,
  delRole,
  addRole,
  editRole,
  getRoleDetail,
  editpermission,
} from "@/api/role";
import { getCompanyMsg } from "@/api/company";
import { getPermissionList } from "@/api/permission";
import { tranListToTreeData } from "@/utils";
import { mapGetters } from "vuex";
export default {
  name: "settins",
  created() {
    this.getRoleList();
  },

  data() {
    return {
      // 高亮tab
      activeName: "role",
      currentId: "",
      pageInfo: {
        // 当前页数
        page: 1,
        // 所有数据数
        total: 0,
        // 每页显示的数据个数
        pagesize: 5,
        // 加载表格loading动画
      },
      loading: false,
      treeloading: false,
      // 角色弹框
      roleForm: {},
      // 公司信息
      form: {},
      // 角色数据
      roleData: [],
      // 权限分配数据
      treeData: [],
      // 权限分配选中数据
      checkedKeys: [],
      defaultProps: {
        label: "name",
        children: "children",
      },
      // 弹窗显示
      showDialog: false,
      showPermDialog: false,

      rules: {
        name: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        description: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    async getRoleList() {
      this.loading = true;

      // 获取角色列表
      let res = await getAllRoles(this.pageInfo);
      // console.log(res);

      // 将返回的角色列表渲染
      this.roleData = res.data.rows;

      // 将返回的总数据进行渲染
      this.pageInfo.total = res.data.total;

      this.loading = false;
    },
    async showPermission(id) {
      this.showPermDialog = true;
      this.treeloading = true;
      this.currentId = id;
      let res = await getPermissionList();
      this.treeData = tranListToTreeData(res.data, "0");
      let res1 = await getRoleDetail(id);
      this.checkedKeys = res1.data.permIds;
      this.treeloading = false;
    },
    async handleClick(tab) {
      switch (tab.name) {
        case "role":
          this.getRoleList();
          break;
        case "company":
          // 将角色管理的当前页码重置为1
          this.pageInfo.page = 1;
          let res = await getCompanyMsg(this.companyId);
          // console.log(res);
          this.form = res.data;
          break;
      }
    },
    cancelBtn() {
      this.roleForm = {};
      this.$refs.roleForm.resetFields();
      this.showDialog = false;
    },
    async addRole() {
      this.$refs.roleForm.validate(async (v) => {
        if (v) {
          this.roleForm.id
            ? await editRole(this.roleForm)
            : await addRole(this.roleForm);
          this.getRoleList();
          this.$message.success(this.title + "成功！");
          this.showDialog = false;
        }
      });
    },
    async editRole(id) {
      let res = await getRoleDetail(id);
      this.roleForm = res.data;
      this.showDialog = true;
    },
    async delRole(id) {
      // 因为$confirm("确定")返回的是Promise对象，所以可以用await
      // .then要触发，执行的是Promise里面的resolve(正常),取消要触发应该是reject(报错)
      try {
        await this.$confirm("确定要删除该角色吗？", "提示", {
          type: "warning",
        });

        await delRole(id);

        if (this.roleData.length == 1 && this.pageInfo.page != 1) {
          this.pageInfo.page--;
        }

        this.getRoleList();
        this.$message.success("删除成功");
      } catch (error) {
        console.log(error);
      }
    },
    async updatePermission() {
      let ids = this.$refs.tree.getCheckedKeys();
      await editpermission({ id: this.currentId, permIds: ids });

      this.$message.success("分配权限成功！");
      this.showPermDialog = false;
    },
    cancelPerm() {
      // 树形数据改为空
      this.treeData = [];
      // 选中的也改为空
      this.checkedKeys = [];
      this.showPermDialog = false;
    },
  },
  computed: {
    ...mapGetters["companyId"],
    title() {
      return this.roleForm.id ? "编辑角色" : "新增角色";
    },
  },
};
</script>

<style lang='scss'>
.setting-container {
  padding: 20px;
  .box-card {
    padding: 20px;
  }
  .el-tabs__content {
    padding: 30px 20px;
  }
  .el-table {
    margin-top: 10px;
    th {
      background-color: #fafafa;
    }
  }
}
</style>